import moment from 'moment';
/**
 * 调用Api 
 * 第四个参数可以传boolen或者object,来控制进度框和按钮
 */
function getApi(action, params, callback){
	let args = arguments;
	console.log(params);
	util.ajax({
		url:action,
		method:'POST',
		data:JSON.stringify(params),
		contentType:'application/json',
		dataType:'json',
		timeout:15000,
		beforeSend:function(xhr){
			/*请求发送前*/			
			if(typeof args[3] == 'object'){
				args[3].addClass('disabled');
			}else if(args.length == 3){
				myApp.showPreloader('加载中...');	
			}
		},
		success:function(xhr){
			/*请求发送成功*/
			if(typeof args[3] == 'object') args[3].removeClass('disabled');
			myApp.hidePreloader();
			callback(xhr);
		},
		error:function(xhr){
			/*请求发送失败*/
			if(typeof args[3] == 'object') args[3].removeClass('disabled');
			myApp.hidePreloader();
			if(xhr.status == 404){
				myApp.alert('服务未找到，请稍后再试。。');								
			}else if(xhr.status == 500){
				myApp.alert('服务出现异常，请稍后再试。');				
			}else{
				myApp.alert('网络状况不佳，请稍后再试。');						
			}
		}
	});	
}

/*
 * 验证手机号
 */
function checkMobile(value) {
	try {
		var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
		return myreg.test(value);
	} catch (ex) {
		return false;
	}
}

/**
 * 显示标题提示框
 */
function showTips(text ,time){
	var toptips = util('.toptips');
	if(toptips.maskTime){
		clearTimeout(toptips.maskTime);
	}
	toptips.html(text);
	toptips.css("display" ,"block");
	toptips.maskTime = window.setTimeout(function () {
        toptips.css('display', 'none');
    }, time?time*1000:2000);
}

/**
 * 将时间戳转换为时间显示
 * @param {float} unixTime	时间戳
 * @param {int} dateType	显示的时间类型:1.yyyy-MM-dd HH:mm; 2.MM-dd HH:mm; 3.yyyy-MM-dd; 4.MM-dd;
 *  								   5.yyyyMMddHHmm; default.yyyy-MM-dd HH:mm:ss
 */
function unixToDate(datetime, dateType) {
	if (datetime == undefined || datetime == null) return "";
	let unixTime, year, month, day, hours, minute, second, time;
	/* 
	 * safari浏览器里 new Date 需要用/来替换- 例如 yyyy-mm-dd  yyyy/mm/dd 
	 * 通过moment.js统一格式化
	 */
	unixTime = new Date(moment(datetime).format('YYYY/MM/DD HH:mm:ss'));
	console.log(unixTime);
	year = unixTime.getFullYear();
	month = unixTime.getMonth() + 1 < 10 ? "0" + (unixTime.getMonth() + 1) : unixTime.getMonth() + 1;
	day = unixTime.getDate() < 10 ? "0" + unixTime.getDate() : unixTime.getDate();
	hours = unixTime.getHours() < 10 ? "0" + unixTime.getHours() : unixTime.getHours();
	minute = unixTime.getMinutes() < 10 ? "0" + unixTime.getMinutes() : unixTime.getMinutes();
	second = unixTime.getSeconds() < 10 ? "0" + unixTime.getSeconds() : unixTime.getSeconds();

	switch (dateType) {
		case 1: //yyyy-MM-dd HH:mm
			return year + "-" + month + "-" + day + " " + hours + ":" + minute;
		case 2: //MM-dd HH:mm
			return month + "-" + day + " " + hours + ":" + minute;
		case 3: //yyyy-MM-dd
			return year + "-" + month + "-" + day;
		case 4: //MM-dd
			return month + "-" + day;
		case 5: //yyyyMMddHHmmss
			return year+''+month+''+day+''+hours+''+minute+''+second;
		default: //yyyy-MM-dd HH:mm:ss
			return year + "-" + month + "-" + day + " " + hours + ":" + minute + ":" + second;
	}
}

/*
 * 时间转换成时间戳
 */
function dateToUnix(dateTime){
	let _dateTime = dateTime.replace(/:/g,'-');
	_dateTime = _dateTime.replace(/ /g,'-');
	let arr = _dateTime.split("-");
	let sysTime;
	if(arr[5]){
		sysTime = new Date(Date.UTC(arr[0],arr[1]-1,arr[2],arr[3]-8,arr[4],arr[5]));			
	}else{
		sysTime = new Date(Date.UTC(arr[0],arr[1]-1,arr[2],arr[3]-8,arr[4]));
	}
	return sysTime.getTime();
}

/*
 * 根据移动端设备分辨率来设置字体 方便使用rem
 */
function appendEmByWidth(){
    let screenW = document.body.clientWidth,
        style = document.createElement('style'),
        size = (screenW / 750) * 20,
        styles = 'html{font-size:' + size + 'px !important;}';
    (document.getElementsByTagName("head")[0] || document.body).appendChild(style);
    if (style.styleSheet) {
        style.styleSheet.cssText = styles;
    }
    else {
        style.appendChild(document.createTextNode(styles));
    }
}

/* 会话缓存   */
function setSessionCache(){
    sessionStorage.setItem(arguments[0], JSON.stringify(arguments[1]));    		
}

function isSessionCache(key){
	if(sessionStorage.getItem(key)){
		return true;
	}else{
		return false;
	}
}

function getSessionCache(key) {
    return JSON.parse(sessionStorage.getItem(key));
}

function deleteSessionCache(key) {
    if (util.isString(key)) {
        util(key.split(',')).each(function () {
            sessionStorage.removeItem(this + '');
        });
    }
}

function clearSessionCache() {
    sessionStorage.clear();
}

/* 本地缓存  */
function setLocalCache(){
   localStorage.setItem(arguments[0], JSON.stringify(arguments[1]));
}

function getLocalCache(key) {
   	return JSON.parse(localStorage.getItem(key));
}

function isLocalCache(key){
	if(localStorage.getItem(key)){
		return true;
	}else{
		return false;
	}
}

function deleteLocalCache(key){
    if (util.isString(key)) {
        util(key.split(',')).each(function () {
            sessionStorage.removeItem(this + '');
        });
    }
}

function clearLocalCache() {
    localStorage.clear();
}

/* 扩展属性end */
/*导出所有方法*/
export default{
	getApi:getApi,
	appendEmByWidth:appendEmByWidth,
	checkMobile:checkMobile,
	showTips:showTips,
	unixToDate:unixToDate,
	dateToUnix:dateToUnix,
	setSessionCache:setSessionCache,
	isSessionCache:isSessionCache,
	getSessionCache:getSessionCache,
	deleteSessionCache:deleteSessionCache,
	clearSessionCache:clearSessionCache,
	setLocalCache:setLocalCache,
	getLocalCache:getLocalCache,
	isLocalCache:isLocalCache,
	deleteLocalCache:deleteLocalCache,
	clearLocalCache:clearLocalCache
}
